package org.takeback.chat.controller;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.time.DateUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.util.WebUtils;
import org.takeback.chat.entity.LHHModel;
import org.takeback.chat.entity.LHHNumDetail;
import org.takeback.chat.entity.LHHPlan;
import org.takeback.chat.entity.Message;
import org.takeback.chat.entity.PubUser;
import org.takeback.chat.lottery.listeners.GameException;
import org.takeback.chat.service.LHHNumDetailService;
import org.takeback.chat.service.LHHPlanService;
import org.takeback.chat.service.LotteryService;
import org.takeback.chat.service.RoomService;
import org.takeback.chat.service.UserService;
import org.takeback.chat.store.room.Room;
import org.takeback.chat.store.room.RoomStore;
import org.takeback.chat.utils.DateUtil;
import org.takeback.chat.utils.MessageUtils;
import org.takeback.mvc.ResponseUtils;
import org.takeback.util.annotation.AuthPassport;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;

@Controller
@RequestMapping({ "/lhh_crl" })
public class LHHPlanController {

	@Autowired
	private RoomService roomService;
	@Autowired
	private RoomStore roomStore;
	
	@Autowired
	LHHPlanService lHHPlanService;
	
	@Autowired
	UserService userService;
	
	@Autowired
	protected LotteryService lotteryService;
	
	@Autowired
	private LHHNumDetailService lhhNumDetailService;
	
	@AuthPassport
	@RequestMapping(value = { "/ya_zhu" }, method = {RequestMethod.GET, RequestMethod.POST })
	public ModelAndView yaZhu(HttpServletRequest request) throws GameException {
		
		
		Integer userId = (Integer) WebUtils.getSessionAttribute(request, "$uid");
		if (userId == null) {
			return ResponseUtils.jsonView(403, "notLogin");
		}
		String roomId = (String) WebUtils.getSessionAttribute(request, "roomId");
		roomId = StringUtils.isBlank(roomId) ? "LHH0001" : roomId;
		Map<String, Object> p = roomService.getRoomProperties(roomId);
		System.out.println(JSON.toJSONString(p));
		//处理结果
//		if(checkResult == null) {//TODO
//			return ResponseUtils.jsonView(200, "false", "押注数据错误");
//		}
		String plan = request.getParameter("plan");
		System.out.println(plan);
		LHHModel lhhModel = null;
		try {
			lhhModel = JSON.parseObject(plan, new TypeReference<LHHModel>() {});
			System.out.println(JSON.toJSONString(lhhModel));
			//设置房间配置
			lhhModel.setP(p);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		if(!(lhhModel.checkPlanOne() == null && lhhModel.checkZHPass() && lhhModel.checkLongHuHe())) {
			return ResponseUtils.jsonView(500, "false", lhhModel.getErrMsg());
		}
		//上次开奖时间
		if(!isIntime(p)) {
			return ResponseUtils.jsonView(500, "false", "已经停止下注！请等待下一场！");
		}
		
		Integer robotAction = Integer.valueOf(p.get("config_lhl_stop_or_start").toString());
//		1表示机器人可以抢，0表示机器停止抢,2表示机器人押注
//		0123  
		if(robotAction == 1) {
			return ResponseUtils.jsonView(500, "false", "已经停止下注！请等待下一场！");
		}
		Room room = roomStore.get(roomId);
		if(!"G07".equals(room.getType())) {
			return ResponseUtils.jsonView(500, "false", "系统繁忙，请重新进入房间！");
		}
		
		LHHPlan lPlan = new LHHPlan();
		lPlan.setCreateTime(new Date());
		lPlan.setUserId(userId);
		lPlan.setRoomId(roomId);
		lPlan.setPlan(plan);
		//用户押注的总金额
		Double money = lhhModel.getTotleMoney().doubleValue();
		//减少当前用户的金额
		int res = lotteryService.moneyDown(userId, money);
		if(res < 1){
			throw new GameException(500, "金额不足,请及时充值!");
		}
		//出去分享金额
		Double leftMone = userService.shareYongjin(userId, money, room);
		//剩下的金额加入到房主的账户
		int result = lotteryService.moneyUp(room.getOwner(), leftMone);
		if(result < 1){
			throw new GameException(500, "房间设置错误请联系管理员!");
		}
		Integer no = lhhNumDetailService.getLhhNum();
		lPlan.setLhhNumDetailId(no+1);
		lHHPlanService.save(LHHPlan.class, lPlan);
//		Message msg = new Message();
//		msg.setContent("某某押注了100单注3");
//		msg.setType(Message.TXT_SYS);
//		MessageUtils.broadcast(room, msg);
		return ResponseUtils.jsonView(200, "success", lPlan);
	}
	

	public static void main(String[] args) {
		String a = "{'one':'c', zh2:[{'z':1}]}";
		LHHModel b = JSON.parseObject(a, new TypeReference<LHHModel>() {});
	}
	
	//是否已经过了开奖时间
	public Boolean isIntime(Map<String, Object> p) {
		Date nowDate = new Date();//当前时间
		//上次开奖时间
		String lastTime = p.get("conf_last_time_task_time").toString();
		Date date = DateUtil.toDate(lastTime);
		//加5分钟后的时间
		Date add5Min = DateUtils.addMinutes(date, 2);
		//提前30秒结束下注
		if((add5Min.getTime() - nowDate.getTime())/1000 < 10) {
			return false;
		}
		return true;
	}
	
	@AuthPassport
	@RequestMapping(value = { "/change_room_status" }, method = { org.springframework.web.bind.annotation.RequestMethod.GET })
	public ModelAndView changeRoom(@RequestParam String status, HttpServletRequest request) {
		Integer userId = (Integer) WebUtils.getSessionAttribute(request, "$uid");
		PubUser user = (PubUser) this.userService.get(PubUser.class, userId);
		if(!"admin".equals(user.getUserId())){
			return ResponseUtils.jsonView(403, "你无权限使用这个功能");
		}
		if (userId == null) {
			return ResponseUtils.jsonView(403, "notLogin");
		}
		roomService.updateLHHConfig(status, "config_lhl_stop_or_start");
		String roomId = (String) WebUtils.getSessionAttribute(request, "roomId");
		Room room = roomStore.get(roomId);
		Message msg = new Message();
		msg.setContent("2".equals(status) ? "请开始押注":"结束押注，等待开奖！");
		msg.setType(Message.TXT_SYS);
		MessageUtils.broadcast(room, msg);
		return ResponseUtils.jsonView(200, "success", null);
	}
	
	
	@RequestMapping({ "/lhh/num_detail" })
	public ModelAndView getPcEggLog(@RequestParam int pageNo, @RequestParam int pageSize, HttpServletRequest request) {
		if (pageNo <= 0) {
			pageNo = 1;
		}
		if (pageSize > 20) {
			pageSize = 20;
		}
		List<LHHNumDetail> list = lhhNumDetailService.getLhhNumdDetailByPage(pageSize, pageNo);
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("list", list);
		map.put("pageNo", pageNo);
		return ResponseUtils.jsonView(200, "success", map);
	}
	
	@RequestMapping({ "/lhh/desc_time" })
	public ModelAndView getPcEggLog(HttpServletRequest request) {
		Map<String, Object> map = new HashMap<String, Object>();
		Date nowDate = new Date();
		map.put("currentTime", nowDate);//系统当前时间
		String roomId = (String) WebUtils.getSessionAttribute(request, "roomId");
		roomId = StringUtils.isBlank(roomId) ? "LHH0001" : roomId;
		Map<String, Object> p = roomService.getRoomProperties(roomId);
		String lastTime = p.get("conf_last_time_task_time").toString();
		map.put("lastOpenTime", lastTime);//上次开奖时间
		Date date = DateUtil.toDate(lastTime);
		
		//加5分钟后的时间 
		Date add5Min = DateUtils.addMinutes(date, 2);
		map.put("nextOpenTime", add5Min);//下次开奖时间
		long minite = (add5Min.getTime() - nowDate.getTime())/1000/60;
		long totalSecon = (add5Min.getTime() - nowDate.getTime())/1000;
		long secon = (add5Min.getTime() - nowDate.getTime())/1000%60;
		map.put("munite",minite);
		map.put("secon", secon);
		map.put("totalSecon", totalSecon);
		
		List<LHHNumDetail> list = lhhNumDetailService.getLhhNumdDetailByPage(0, 1);
//		lPlan.setLhhNumDetailId(no+1);
		String str = "";
		LHHNumDetail l = list.get(0);
		if( Integer.parseInt(l.getNum1()) > Integer.parseInt(l.getNum5())){
			 str = "龙";
		} else if(Integer.parseInt(l.getNum1()) < Integer.parseInt(l.getNum5())) {
			 str = "虎";
		} else if(Integer.parseInt(l.getNum1()) == Integer.parseInt(l.getNum5())){
			 str = "合";
		}
		map.put("lhhType", str);
		map.put("qishu", l.getId());
		map.put("lhhNum", l.getNum1()+l.getNum2()+l.getNum3()+l.getNum4()+l.getNum5());
		if(!isIntime(p)) {
			map.put("isInTime", false);
		} else {
			map.put("isInTime", true);
		}
		return ResponseUtils.jsonView(200, "success", map);
	}
}
